package com.histone.grab_ticket.web;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/demo")
public class DemoController {

    private static Logger logger = LoggerFactory.getLogger(DemoController.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @RequestMapping("/lock")
    public String lock(@RequestParam("sid") String serverId) {

        RLock lock = redissonClient.getLock("ev20180710-success");
        try {
            lock.lock();
            String success = redisTemplate.opsForValue().get("ev20180710-success");
            if ("no".equalsIgnoreCase(success)) {
                logger.info(serverId + "get the ticket");
                redisTemplate.opsForValue().set("ev20180710-success", serverId);
                return "success";
            } else {
                logger.info(serverId + "fail, it belong to " + success);
                return "fail";
            }
        } catch (Exception ex) {
            logger.error("Error occurred");
        } finally {
            lock.unlock();
        }

        return "lock-" + "[" + serverId +"]";
    }

}
